# -*- coding=utf-8 -*-
import re
from Record import RecordIP

record_file = '../data/record_ip.txt'
recorder = RecordIP( record_file )

uri_record  = re.compile(u'/record(/[^/?\']+)*$')
uri_look    = re.compile(u'/look(/[^/?\']+)*$')

def application(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)

    r = uri_record.match(environ['REQUEST_URI'])
    l = uri_look.match(environ['REQUEST_URI'])
    if r is not None :
        flag = r.group(1)
        if flag is not None and len(flag) > 1:
            flag = flag[1:]
            recorder.record(flag, environ['HTTP_X_FORWARDED_FOR'])
            recorder.export()
        # pass
        # if RecordIP( environ ) :
        return ['Record OK\n']
    elif l <> None:
        return ['{0}={1}\n'.format(k, recorder.cache[k])
                for k in sorted(recorder.cache)]
    else:
        return ['Hello world!\n'] + \
                ['{0}={1}\n'.format(k,environ[k])
                                     for k in sorted(environ)]

if __name__ == 'wsgi' :
    recorder.init()
    pass

